﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Basic;
using Interface;

namespace Client
{
    /// <summary>
    /// 异步操作辅助（通过协程实现）
    /// </summary>
    public class AsyncActionHelper : MonoBehaviour
    {
        static AsyncActionHelper()
        {
            var obj = new GameObject();
            obj.name = "AsyncHelper";
            DontDestroyOnLoad(obj);
            obj.hideFlags = HideFlags.HideAndDontSave;
            Instance = obj.AddComponent<AsyncActionHelper>();
        }

        public static AsyncActionHelper Instance
        {
            get;
            private set;
        }

        /// <summary>
        /// 下一帧执行指定操作
        /// </summary>
        /// <param name="callback"></param>
        public void DoActionNextFrame(Action callback)
        {
            StartCoroutine(doActionNextFrame(callback));
        }
        private IEnumerator doActionNextFrame(Action callback)
        {
            yield return null;
            if (callback != null)
            {
                callback();
            }
        }

        /// <summary>
        /// 帧结束时执行指定操作
        /// </summary>
        /// <param name="callback"></param>
        public void DoActionFrameEnd(Action callback)
        {
            StartCoroutine(doActionFrameEnd(callback));
        }
        private IEnumerator doActionFrameEnd(Action callback)
        {
            yield return new WaitForEndOfFrame();
            if (callback != null)
            {
                callback();
            }
        }
    }
}
